package com.yj.auto.core.web.common.controller;

import java.util.List;

import com.jfinal.core.ActionKey;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.yj.auto.Constants;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.base.online.SessionUser;
import com.yj.auto.core.base.online.SessionUserUtil;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.web.system.model.Atta;
import com.yj.auto.core.web.system.model.Org;
import com.yj.auto.core.web.system.model.Resource;
import com.yj.auto.core.web.system.model.User;
import com.yj.auto.core.web.system.model.UserRole;
import com.yj.auto.core.web.system.service.ResourceService;
import com.yj.auto.core.web.system.service.UserService;
import com.yj.auto.helper.AutoHelper;
import com.yj.auto.helper.LogHelper;
import com.yj.auto.plugin.lucene.model.IndexModel;
import com.yj.auto.plugin.lucene.model.ResultModel;
import com.yj.auto.plugin.lucene.utils.LuceneUtil;

/**
 * 
 */
public class IndexController extends BaseController {
	private static Log logger = Log.getLog(IndexController.class);

	@ActionKey("/")
	public void index() {
		render("index.html");
	}

	// 生成图片验证码
	@ActionKey("/captcha")
	public void captcha() {
		renderCaptcha();
	}

	@ActionKey("/login")
	public void login(String username, String pwd) {
		boolean valid = this.validateCaptcha("captcha");
		if (1 == 2 && !valid) {
			this.keepPara();
			index();
			this.setAttr("error", "验证码错误");
		} else if (!validate(username, pwd)) {
			this.keepPara();
			index();
		} else {
			render("main.html");
		}
	}

	private boolean validate(String username, String pwd) {
		String msg = null;
		if (StrKit.isBlank(username) || StrKit.isBlank(pwd)) {
			msg = "登录账号或者密码不能为空";
		} else {
			UserService userSrv = AutoHelper.getUserService();
			User user = userSrv.getByCode(username);
			if (null == user) {
				msg = "登录账号不存在";
			} else if (!SecureUtil.md5(pwd).equals(user.getPwd())) {
				msg = "密码错误";
			} else if (!Constants.IS_VALID_DATA(user.getState())) {
				msg = "无效用户,请联系管理员";
			} else {
				List<UserRole> list = userSrv.getRoles(user.getId());
				Integer[] roles = new Integer[list.size()];
				for (int i = 0; i < list.size(); i++) {// 用户角色组
					roles[i] = list.get(i).getRoleId();
				}
				SessionUser su = SessionUserUtil.addSessionUser(getRequest(), user.getId(), user.getCode(), user.getName(), user.getOrgId(), roles);
				if (null != user.getOrgId()) {// 用户单位名称
					List<Org> orgs = AutoHelper.getOrgService().findOrgs(user.getOrgId());
					String title = "";
					for (Org o : orgs) {
						if (!"".equals(title)) {
							title += "-";
						}
						title += o.getName();
					}
					su.setAttr("orgName", title);
				}
				String photo = Constants.USER_DEFAULT_PHOTO;// 用户头像
				Atta atta = AutoHelper.getAttaService().getByData(UserService.ATTA_USER_PHOTO, user.getId());
				if (null != atta) {
					photo = atta.getUri();
				}
				su.setAttr("photo", photo);

				LogHelper.addLoginLog(getRequest());// 登录日志
			}
		}
		this.setAttr("error", msg);
		return null == msg;
	}

	@ActionKey("/logout")
	public void logout() {
		this.getSession().invalidate();
		this.index();
	}

	@ActionKey("/welcome")
	public void welcome() {
		render("welcome.html");
	}

	@ActionKey("/help")
	public void help() {
		render("help.html");
	}

	@ActionKey("/menu")
	public void menu() {
		Integer parentId = getParaToInt();
		ResourceService resourceSrv = AutoHelper.getResourceService();
		List<Resource> list = resourceSrv.children(parentId, this.getSuId());
		for (Resource r : list) {
			Resource temp = resourceSrv.getCache(r.getId());
			if (null != temp) {
				r.setIsParent(temp.getIsParent());
			}
		}
		ResponseModel<List<Resource>> res = new ResponseModel<List<Resource>>(true);
		res.setData(list);
		renderJson(res);
	}

	@ActionKey("/search")
	public void search() {
		int page = getParaToInt(0, 1);
		//setAttr("lucene_index_page", page);
		String keyword = getPara("keyword");
		boolean success = false;
		String msg = "搜索关键字不能为空";
		ResultModel result = null;
		if (StrKit.notBlank(keyword)) {
			try {
				result = LuceneUtil.search(page, keyword);
				success = true;
			} catch (Exception e) {
				logger.error("index search error:", e);
				msg = e.getMessage();
			}
		}
		ResponseModel<ResultModel> res = new ResponseModel<ResultModel>();
		res.setSuccess(success);
		res.setMsg(msg);
		res.setData(result);
		setAttr("result", res);
		render("search.html");
	}
}